package com.szly.phm.admin.security;


import com.alibaba.fastjson.JSONObject;
import com.szly.phm.admin.utils.IPUtils;
import com.szly.phm.common.entity.po.SysLog;
import com.szly.phm.common.entity.vo.login.LoginPermissionVO;
import com.szly.phm.common.entity.vo.permissiom.PermissionTreeVO;
import com.szly.phm.common.mapper.SysLogMapper;
import com.szly.phm.common.service.ISysPermissionService;
import com.szly.phm.common.service.ISysRoleService;
import com.szly.phm.common.service.ISysUserService;
import com.szly.phm.common.utils.BeanCopyUtils;
import com.szly.phm.common.utils.HandleUtils;
import com.szly.phm.common.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * token过滤器验证token有效性
 *
 * @author chengjiang
 * @date
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    // 令牌自定义标识头
    @Value("${com.phm.token.tokenHeader}")
    private String tokenHeader;

    // 令牌自定义前缀
    @Value("${com.phm.token.tokenPrefix}")
    private String tokenPrefix;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPermissionService permissionService;



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String newToken;
        // 根据表示头获取token数据
        var token = request.getHeader(tokenHeader);
        // 解析token,获取用户Id
        if (StringUtils.isNotBlank(token) && token.startsWith(tokenPrefix)) {
            token = token.replace(tokenPrefix, "");
            var userId = TokenUtils.parseToken(token, "secretKey");
            if (StringUtils.isNotBlank(token)) {
                //验证token
                try {
                    newToken=TokenUtils.verify(userId,token, "secretKey");

                } catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }
                if (StringUtils.isNotBlank(userId)) {
                    var user = userService.getById(userId);
                    if (user != null && !user.getIsSoftDelete()) {
                        var loginUser = new LoginUser();
                        loginUser.setNewToken(newToken);
                        BeanCopyUtils.copy(user, loginUser);
                        loginUser.setUserId(user.getId());
                        loginUser.setToken(token);
                        //查询角色
                        var roles = roleService.queryRolesByUserId(user.getId());
                        loginUser.setRoles(roles);
                        //查询权限
                        var roleIds = new ArrayList<String>();
                        //是否超级管理员
                        AtomicBoolean supperAdmin = new AtomicBoolean(false);
                        if (HandleUtils.ListIsNotNull(roles)) {
                            loginUser.setRoleId(roles.get(0).getId());
                            loginUser.setRoleName(roles.get(0).getRoleName());
                            roles.forEach(r -> {
                                roleIds.add(r.getId());
                                if ("超级管理员".equals(r.getRoleName())) {
                                    supperAdmin.set(true);
                                }
                            });
                        }
                        var permissions = permissionService.queryPermissionsByRoleIds1(roleIds, supperAdmin);
                        loginUser.setUserPermissions(permissions);
                        //授权
                        var auth = new ArrayList<SimpleGrantedAuthority>();
                        if (supperAdmin.get()) {
                            //如果是超级管理员
                            auth.add(new SimpleGrantedAuthority("supperAdmin"));
                        } else {
                            for ( PermissionTreeVO lp : permissions) {
                                auth.add(new SimpleGrantedAuthority(lp.getRouter()));
                            }
                        }
                        loginUser.setAuthorities(auth);
                        //  给系统用的哪里都可以获取到用户的权限
                        var authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    } else {
                        SecurityContextHolder.clearContext();
                    }
                } else {
                    SecurityContextHolder.clearContext();
                }
            } else {
                SecurityContextHolder.clearContext();
            }
        } else {
            SecurityContextHolder.clearContext();
        }
        filterChain.doFilter(request, response);
    }

}
